﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class apportion4 : System.Web.UI.Page
    {
        public string BillYear
        {
            get
            {
                if (Request.QueryString["iYear"] != null) return Request.QueryString["iYear"].ToString();
                else return "2012";
            }

        }

        public string BillMonth
        {
            get
            {
                if (Request.QueryString["iMonth"] != null) return Request.QueryString["iMonth"].ToString();
                else return "01";
            }

        }

        public decimal CostDiff
        {
            get
            {
                if (Request.QueryString["CostDiff"] != null) return System.Convert.ToDecimal(Request.QueryString["CostDiff"].ToString());
                else return 0;
            }

        }

        public decimal RevenueDiff
        {
            get
            {
                if (Request.QueryString["RevenueDiff"] != null) return System.Convert.ToDecimal(Request.QueryString["RevenueDiff"].ToString());
                else return 0;
            }

        }





        private void BindTree()
        {
            SystemBll bll = new SystemBll();

            DataTable dt = bll.BuildAllProductCategory();

            DataRow[] rows2 = dt.Select("parentGUID is null");

            foreach (DataRow row in rows2)
            {
                TreeNode node = CreateNode(row["categoryName"].ToString(), true, row["categoryGUID"].ToString());
                if (!row["categoryName"].ToString().Contains("维护") && !row["categoryName"].ToString().Contains("销售返利")) { node.Checked = true; }
                //node.Checked = true; //row["IsChecked"].ToString() == "1" ? true : false;
                treeProductCategory.Nodes.Add(node);

                RecursivelyPopulate2(dt, node);
            }

        }

        private TreeNode CreateNode(string text, bool expanded, string id)
        {
            TreeNode node;
            node = new TreeNode(text, id);
            node.Expanded = expanded;
            node.SelectAction = TreeNodeSelectAction.None;
            return node;
        }

        private void RecursivelyPopulate2(DataTable dt, TreeNode node)
        {
            DataRow[] rows = dt.Select("parentGUID = '" + node.Value + "'");
            foreach (DataRow row in rows)
            {
                TreeNode TreeNode = CreateNode(row["categoryName"].ToString(), false, row["categoryGUID"].ToString());
                if (!row["categoryName"].ToString().Contains("维护") && !row["categoryName"].ToString().Contains("销售返利")) { TreeNode.Checked = true; }
                node.ChildNodes.Add(TreeNode);
                RecursivelyPopulate2(dt, TreeNode);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                treeProductCategory.Attributes.Add("OnClick", "OnTreeNodeChecked()");
                BindTree();
            }

        }
        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string sYear, sMonth, sCategoryCode="";

            List<BGSalesBillsEntity> list;
                
            decimal totalMoney = 0;//税后金额
            decimal apportionAmount_has = 0;
            decimal apportionAmount_tmp = 0;
            
            int loop_amount = 0;

            int loop_amount_tmp = 0;

            
            foreach (TreeNode item in this.treeProductCategory.CheckedNodes)
            {
                if (item.Checked)
                {

                    CtrtInstrumentCategoryEntity categoryentity = new SystemBll().Get<CtrtInstrumentCategoryEntity>(new Guid(item.Value));
                    if (categoryentity != null)
                    { sCategoryCode = categoryentity.categoryCode; }
                    if (item.ChildNodes.Count == 0)
                    {

                        list = new SystemBll().GetAll<BGSalesBillsEntity>(" and cCusCode not in(select customerCode from cms_Bg_InnerCustomer) and SourceType != 3 and cCategoryCode like '" + sCategoryCode + "%' and billYear=" + BillYear + " and billMonth=" + BillMonth);
                        foreach (BGSalesBillsEntity entity in list)
                        {
                            totalMoney += entity.iNatMoney + entity.iNatMoney_adjust + entity.SaleAmount2;
                        }
                        
                    }
                }

                
            }

            //被分摊的现金折扣（收入）
            decimal apportionAmount = 0;
            
            BillBll bll = new BillBll();

            list = new SystemBll().GetAll<BGSalesBillsEntity>(" and cCusCode not in(select customerCode from cms_Bg_InnerCustomer) and SourceType != 3 and cInvCode= 'xjzk' and billYear=" + BillYear + " and billMonth=" + BillMonth);
            foreach (BGSalesBillsEntity entity in list)
            {
                //entity.Cost2 = CostDiff * ((entity.iNatMoney + entity.iNatMoney_adjust) / totalMoney);
                entity.SaleAmount4 = (entity.iNatMoney + entity.iNatMoney_adjust) * (-1);
                bll.InsertOrUpdate(entity);
                apportionAmount += entity.iNatMoney + entity.iNatMoney_adjust;
            }

            foreach (TreeNode item in this.treeProductCategory.CheckedNodes)
            {
                if (item.Checked)
                {

                    CtrtInstrumentCategoryEntity categoryentity = new SystemBll().Get<CtrtInstrumentCategoryEntity>(new Guid(item.Value));
                    if (categoryentity != null)
                    { sCategoryCode = categoryentity.categoryCode; }
                    if (item.ChildNodes.Count == 0)
                    {

                        list = new SystemBll().GetAll<BGSalesBillsEntity>(" and cCusCode not in(select customerCode from cms_Bg_InnerCustomer) and SourceType != 3 and cCategoryCode like '" + sCategoryCode + "%' and billYear=" + BillYear + " and billMonth=" + BillMonth);
                        foreach (BGSalesBillsEntity entity in list)
                        {
                            apportionAmount_tmp = Math.Round((apportionAmount * ((entity.iNatMoney + entity.iNatMoney_adjust + entity.SaleAmount2) / totalMoney) - Convert.ToDecimal("0.001")), 2);
                            apportionAmount_has += apportionAmount_tmp;
                            entity.SaleAmount4 = apportionAmount_tmp;

                            //entity.SaleAmount4 = apportionAmount * ((entity.iNatMoney + entity.iNatMoney_adjust + entity.SaleAmount2) / totalMoney);
                            bll.InsertOrUpdate(entity);
                        }

                    }
                }

            }

            BillBll bll1 = new BillBll();

            loop_amount = Math.Abs(Convert.ToInt32((apportionAmount_has - apportionAmount) * 100));

            list = new SystemBll().GetAll<BGSalesBillsEntity>(" and cInvCode!= 'xjzk' and SaleAmount4 !=0 and billYear=" + BillYear + " and billMonth=" + BillMonth, " order by SaleAmount4 asc");
            foreach (BGSalesBillsEntity entity in list)
            {
                loop_amount_tmp++;
                if (loop_amount_tmp > loop_amount) { break; }
                entity.SaleAmount4 = entity.SaleAmount4 + Convert.ToDecimal("0.01");
                bll1.InsertOrUpdate(entity);

            }


            txtResult.Text += "分摊已完成，参与分摊金额为"+totalMoney.ToString();
            new BillBll().updateApportion3Status( Convert.ToInt16(BillYear), Convert.ToInt16(BillMonth), "1");


        }



    }
}


